<?php
class Thread extends AppModel {
	public $name = 'Thread';
	public $tablePrefix = 'cakeforum_';

	public $hasMany = array(
		'Notification' => array(
			'className' => 'Notification',
			'foreignKey' => 'thread_id',
			'condition' => array('thread_id' => 'Parent.id')
		)
	);



	public $belongsTo = array(
		'User' => array(
			'counterCache' => true,
			'foreignKey' => 'user_id',
			'fields' => 'id, username, created, role, thread_count, user_file_path, user_file_name, user_content_type'
		),
		'LatestUser' => array(
			'foreignKey' => 'latest_reply_user_id',
			'className' => 'User',
			'fields' => 'id, username, created'
		),
		'EditUser' => array(
			'foreignKey' => 'lasteditor',
			'className' => 'User',
			'fields' => 'id, username'
		),
		'Thread2' => array(
			'counterCache' => 'topic_count',
			'counterScope' => array('Thread.thread_id' => 0),
			'foreignKey' => 'sub_forum_id',
			'className' => 'SubForum',
			'fields' => 'id'
		),
		'SubForum' => array(
			'counterCache' => 'thread_count',
			'counterScope' => array('Thread.thread_id <> 0'),
			'foreignKey' => 'sub_forum_id',
			'className' => 'SubForum',
			'fields' => 'id, name'
		),
		'Parent' => array(
			'counterCache' => 'reply_count',
			'foreignKey' => 'thread_id',
			'className' => 'Thread',
			'fields' => 'id, reply_count'
		),
	);

	public $validate = array(
		'title' => array(
			'required1' => array(
				'rule' => 'notEmpty',
				'message' => 'Please enter a title'
			),
		),
		'body' => array(
			'required3' => array(
				'rule' => 'notEmpty',
				'message' => 'Please enter a message'
			),
		),
		'editreason' => array(
			'required' => array(
				'rule' => 'notEmpty',
				'message' => 'Please enter a reason for editing this thread'
			)
		)
	);

	public function isOwnedBy($threadId) {
		if(AuthComponent::User('role') == "3"){
			return true;
		}elseif(AuthComponent::User('role') == "2"){
			$this->id = $threadId;
			$threadData = $this->read();
			$threadRole = $threadData['User']['role'];

			if($this->field('id', array('id' => $threadId, 'user_id' => AuthComponent::User('id'))) === $threadId){
				return true;
			}else{
				return (AuthComponent::User('role') > $threadRole) ? true : false;
			}
		}elseif(AuthComponent::User('role') == "1"){
			return $this->field('id', array('id' => $threadId, 'user_id' => AuthComponent::User('id'))) === $threadId;
		}
	}

	public function afterSave($created){
		// true on create, false on update

	}

	public function postThread($data = null, $threadId = '0'){
		$this->set($data);
		$this->set('user_id', AuthComponent::User('id'));
		$this->set('thread_id', $threadId);
		$this->set('latest_reply_user_id', AuthComponent::User('id'));
		$this->set('latest_reply_created', date('Y-m-d H:i:s', time()));
		$this->set('ip', $_SERVER['REMOTE_ADDR']);
;
		if($this->save($this->data)){
			$notificationThreadId = ($threadId == '0') ? $this->id : $threadId;
			$this->saveField('latest_reply_thread_id', $this->id);
			if($data['Thread']['notification']){
				$this->Notification->addNotification($notificationThreadId);
			}
			return true;
		}
		return false;
	}

	public function updateParent($data = null, $parentId, $newThreadId){
		$parentData = array(
			'id' => $parentId,
			'latest_reply_user_id' => AuthComponent::User('id'),
			'latest_reply_created' => date('Y-m-d H:i:s', time()),
			'latest_reply_thread_id' => $newThreadId
		);
		if($this->save($parentData)){
			/* Once parent thread is updated
			* delete any notification subscriptions
			* the user may have for this thread
			*
			* If user checked the subscribe box
			* add new subscription
			*/
			$this->Notification->deleteAll(array('thread_id' => $parentId, 'user_id' => AuthComponent::User('id')));
			if($data[$this->alias]['notification']){
				$this->Notification->addNotification($parentId);
			}

			/* Grab parent thread data to be used in notification email */
			$this->id = $parentId;
			$this->recursive = -1;
			$parentData = $this->read();

			/* Send notification emails to anyone subscribed to this thread
			* Don't send email to self
			*/
			$this->Notification->sendAll($parentData, $newThreadId);

			return true;
		}
		return false;
	}

	public function postReply($data = null, $parentId = null){
		/* Post a reply to a parent thread */
		$this->Create();
		$this->set($data);
		$this->set('user_id', AuthComponent::User('id'));
		$this->set('thread_id', $parentId);
		$this->set('ip', $_SERVER['REMOTE_ADDR']);

		if($this->postThread($data, $parentId)){
			return true;
		}
	}

	public function editThread($data = null, $threadId = null){
		$this->set($data);
		$this->set('lasteditor', AuthComponent::User('id'));
		if($this->save($this->data)){
			if($data[$this->alias]['notification']){
				$this->Notification->deleteAll(array('thread_id' => $this->id, 'user_id' => AuthComponent::User('id')));
				$this->Notification->addNotification($threadId);
			}else{
				$this->Notification->deleteAll(array('thread_id' => $this->id, 'user_id' => AuthComponent::User('id')));
			}
			return true;
		}
		return false;
	}

	public function whoCanEdit($threads){
		/* Add canEdit key to threads
		* Threads the user can edit have an edit icon
		*/
		$i = 0;
		while($i < count($threads)){
			$threads[$i]['Thread']['canEdit'] = ($this->isOwnedBy($threads[$i]['Thread']['id'])) ? 1 : 0;
			$i++;
		}
		return $threads;
	}


	public function getQuotedThread($threadId){
		/* If quoteId is specified, see if that thread exists
		* If it does grab the body and put a > in front of each line
		* Adds author of thread and time of posting above quote
		*/
		$this->id = $threadId;
		if($this->exists()){
			$threadData = $this->read();
			$body = str_repeat(PHP_EOL, 4);
			$body .= '> **' . $threadData['User']['username'] . ' wrote at ' . $threadData[$this->alias]['created'] . '**' . PHP_EOL . '> ' . PHP_EOL;
			foreach(explode(PHP_EOL, $threadData['Thread']['body']) as $line){
				$body .= '> ' . $line . PHP_EOL;
			}
		}else{
			$body = '';
		}
		return $body;
	}

	public function locked($id = null){
		return ($this->field('locked', $id)) ? true : false;
	}

	public function isParent($id = null){
		return ($this->field('thread_id') == '0') ? true : false;
	}

	public function incrementViews(){
		$this->id;
		$this->query("UPDATE " . $this->tablePrefix . $this->useTable . " SET views = views+1 WHERE thread_id = 0 AND id = " . $this->id);
		return true;
	}
}